package com.jww.dao.user;

import com.jww.dao.BaseDao;
import com.jww.pojo.Role;
import com.jww.pojo.User;
import com.mysql.jdbc.StringUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class UserDaoImpl implements UserDao {
    // 用户登录
    @Override
    public User getLoginUser(Connection conn, String userCode) throws SQLException {
        PreparedStatement ps = null;
        ResultSet rs = null;
        User user = null;

        if (conn != null) {
            String sql = "select * from smbms_user where userCode=?";
            Object[] params = { userCode };

            rs = BaseDao.execute(conn, ps, rs, sql, params);

            if (rs.next()) {
                user = new User();
                user.setId(rs.getInt("id"));
                user.setUserCode(rs.getString("userCode"));
                user.setUserName(rs.getString("userName"));
                user.setUserPassword(rs.getString("userPassword"));
                user.setGender(rs.getInt("gender"));
                user.setBirthday(rs.getDate("birthday"));
                user.setPhone(rs.getString("phone"));
                user.setAddress(rs.getString("address"));
                user.setUserRole(rs.getInt("userRole"));
                user.setCreatedBy(rs.getInt("createdBy"));
                user.setCreationDate(rs.getDate("creationDate"));
                user.setModifyBy(rs.getInt("modifyBy"));
                user.setModifyDate(rs.getDate("modifyDate"));
            }
            BaseDao.closeResource(null, ps, rs);
        }
        return user;
    }

    // 用户修改密码
    @Override
    public int updatePwd(Connection conn, int id, String password) throws SQLException {
        PreparedStatement ps = null;
        int execute = 0;
        if (conn != null) { // 如果数据库不为空
            // 修改语句sql
            String sql = "update smbms_user set userPassword=? where id=?";
            Object[] params = { password, id };// 传入参数 对应占位符的顺序
            execute = BaseDao.execute(conn, ps, sql, params);
            // 关闭资源
            BaseDao.closeResource(null, ps, null);
        }
        return execute;
    }

    // 查询用户总数 根据用户名或者职位
    @Override
    public int getUserCount(Connection conn, String username, int userRole) throws SQLException {
        PreparedStatement ps = null;
        ResultSet rs = null;
        int count = 0;
        // 数据库不能空
        if (conn != null) {
            // 因为这里需要拼接所以需要用StringBuffer
            StringBuffer sql = new StringBuffer();
            // 查询总数
            sql.append("select count(1) as count from smbms_user u,smbms_role r where u.userRole = r.id");
            // 存放我们的参数
            ArrayList<Object> list = new ArrayList<>();

            if (!StringUtils.isNullOrEmpty(username)) {
                sql.append(" and u.userName like ?");
                list.add("%" + username + "%"); // 这里是模糊查询所以要加上% % 占位符？->username
            }

            if (userRole > 0) {
                sql.append(" and u.userRole = ?"); // 注意空格
                list.add(userRole);
            }

            // 怎么把List转换为数组
            Object[] params = list.toArray();

            System.out.println("UserDaoImpl->getUserCount:" + sql.toString()); // 输出最后完成的sql语句
            // 结果集
            rs = BaseDao.execute(conn, ps, rs, sql.toString(), params);
            if (rs.next()) {
                // 从结果集中获取最终的数量
                count = rs.getInt("count");
            }
            // 关闭资源
            BaseDao.closeResource(null, ps, rs);
        }
        return count;
    }

    // 查询用户列表
    @Override
    public List<User> getUserList(Connection conn, String username, int userRole, int currentPageNo, int pageSize)
            throws SQLException {
        PreparedStatement ps = null;
        ResultSet rs = null;
        List<User> userList = new ArrayList<User>();
        if (conn != null) {
            StringBuffer sql = new StringBuffer();
            sql.append("select u.*,r.roleName as userRoleName from smbms_user u,smbms_role r where u.userRole = r.id");
            List<Object> list = new ArrayList<Object>();
            if (!StringUtils.isNullOrEmpty(username)) {
                sql.append(" and u.userName like ?");
                list.add("%" + username + "%");
            }
            if (userRole > 0) {
                sql.append(" and u.userRole = ?");
                list.add(userRole);
            }
            /*
             * 分页sql
             * limit ?,?
             * 第一个占位符 是 offset（偏移量），表示 跳过多少条
             * 第二个占位符 是pageSize（每页条数）， 表示取多少条都行（固定）
             * offset = (页码-1) * pageSize
             * 比如前端页面 ： 第1页 每页 5条 0，5 （1 2 3 4 5）
             * 第2页 每页 5条 5，5 （6 7 8 9 10）
             * 第3页 每页 5条 10，5 （11 12 13 14 15）
             * 新一页的第一条数据 = offset + 1
             */
            sql.append(" order by creationDate DESC limit ?,?");
            // 计算offset 也是当前页面
            currentPageNo = (currentPageNo - 1) * pageSize;
            list.add(currentPageNo);
            list.add(pageSize);
            // 转换成数组
            Object[] params = list.toArray();
            // 代码测试
            System.out.println("UserDaoImpl->getUserList:" + sql.toString());
            rs = BaseDao.execute(conn, ps, rs, sql.toString(), params);
            // 查询的数据，如果有就往下走
            while (rs.next()) {
                User user = new User();
                user.setId(rs.getInt("id"));
                user.setUserCode(rs.getString("userCode"));
                user.setUserName(rs.getString("userName"));
                user.setGender(rs.getInt("gender"));
                user.setBirthday(rs.getDate("birthday"));
                user.setPhone(rs.getString("phone"));
                user.setAddress(rs.getString("address"));
                user.setUserRole(rs.getInt("userRole"));
                user.setUserRoleName(rs.getString("userRoleName"));
                userList.add(user);
            }
            // 关闭资源
            BaseDao.closeResource(null, ps, rs);
        }
        return userList;
    }

    //添加用户
    @Override
    public int add(Connection conn, User user) throws SQLException {
        PreparedStatement ps = null;
        int updateRows = 0;

        if (conn != null) {
            String sql = "insert into smbms_user (userCode, userName, userPassword, " +
                    "gender, birthday, phone, address, userRole, createdBy, creationDate)" +
                    "values (?,?,?,?,?,?,?,?,?,?)";
            // 测试代码
            System.out.println("UserDaoImpl->add:" + sql);
            Object[] params = { user.getUserCode(), user.getUserName(), user.getUserPassword(), user.getGender(),
                    user.getBirthday(), user.getPhone(), user.getAddress(),
                    user.getUserRole(), user.getCreatedBy(), user.getCreationDate() };
            // 增加
            updateRows = BaseDao.execute(conn, ps, sql, params);
            // 关闭内存
            BaseDao.closeResource(null, ps, null);
        }
        return updateRows;
    }

    // 删除用户
    @Override
    public int deleteUserById(Connection conn, int id) throws SQLException {
        PreparedStatement ps = null;
        int updateRows = 0;
        if (conn != null) {
            String sql = "delete from smbms_user where id=?";
            // 测试代码
            System.out.println("UserDaoImpl->delete:" + sql);
            Object[] params = { id };
            updateRows = BaseDao.execute(conn, ps, sql, params);
            BaseDao.closeResource(null, ps, null);
        }
        return updateRows;
    }

    // 修改用户信息
    public int modify(Connection connection, User user) throws Exception {
        int flag = 0;
        PreparedStatement pstm = null;
        if(null != connection){
            String sql = "update smbms_user set userName=?,"+
                    "gender=?,birthday=?,phone=?,address=?,userRole=?,modifyBy=?,modifyDate=? where id = ? ";
            Object[] params = {user.getUserName(),user.getGender(),user.getBirthday(),
                    user.getPhone(),user.getAddress(),user.getUserRole(),user.getModifyBy(),
                    user.getModifyDate(),user.getId()};
            flag = BaseDao.execute(connection, pstm, sql, params);
            BaseDao.closeResource(null, pstm, null);
        }
        return flag;
    }

    // 通过userId查询user
    public User getUserById(Connection connection, String id) throws Exception {
        User user = null;
        PreparedStatement pstm = null;
        ResultSet rs = null;
        if(null != connection){
            String sql = "select u.*,r.roleName as userRoleName from smbms_user u,smbms_role r where u.id=? and u.userRole = r.id";
            Object[] params = {id};
            rs = BaseDao.execute(connection, pstm, rs, sql, params);
            if(rs.next()){
                user = new User();
                user.setId(rs.getInt("id"));
                user.setUserCode(rs.getString("userCode"));
                user.setUserName(rs.getString("userName"));
                user.setUserPassword(rs.getString("userPassword"));
                user.setGender(rs.getInt("gender"));
                user.setBirthday(rs.getDate("birthday"));
                user.setPhone(rs.getString("phone"));
                user.setAddress(rs.getString("address"));
                user.setUserRole(rs.getInt("userRole"));
                user.setCreatedBy(rs.getInt("createdBy"));
                user.setCreationDate(rs.getTimestamp("creationDate"));
                user.setModifyBy(rs.getInt("modifyBy"));
                user.setModifyDate(rs.getTimestamp("modifyDate"));
                user.setUserRoleName(rs.getString("userRoleName"));
            }
            BaseDao.closeResource(null, pstm, rs);
        }
        return user;
    }
}
